package com.extension.company.dao.daoUtil;

import android.content.Context;


import com.extension.company.dao.DaoMaster;
import com.extension.company.dao.DaoSession;

import org.greenrobot.greendao.query.QueryBuilder;

/**
 * 作者：zwk
 * 时间：on 2019/2/25 20:42
 * 功能：创建数据，创建数据库的表， 包含书库的crud ，对数据的升级
 */
public class DaoManger {

	private static final String TAG = DaoManger.class.getSimpleName();
	private static final String DB_NAME = "company.sqlite";
	private volatile static DaoManger manger;
	private static DaoMaster.DevOpenHelper helper;
	private static DaoMaster daoMaster;
	private static DaoSession daoSession;
	private Context context;

	/**
	 * 使用单例模式获得操作数据库的对象
	 *
	 * @return
	 */
	public static DaoManger getInstance() {
		DaoManger instance = null;
		if (manger == null) {
			synchronized (DaoManger.class) {
				if (instance == null) {
					instance = new DaoManger();
					manger = instance;
				}
			}
		}else {
			instance=manger;
		}

		return instance;
	}

	public void init(Context context) {
		this.context = context;
	}

	/**
	 * 判断是否村子数据库，如果没有则创建数据库
	 *
	 * @return
	 */
	public DaoMaster getDaoMaster() {
		if (daoMaster == null) {
			DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME);
			daoMaster = new DaoMaster(helper.getWritableDatabase());
		}
		return daoMaster;
	}

	/**
	 * 完成数据的添加、删除、修改、查询的操作 ，仅仅是一个接口
	 *
	 * @return
	 */
	public DaoSession getDaoSession() {
		if (daoSession == null) {
			if (daoMaster == null) {
				daoMaster = getDaoMaster();
			}
			daoSession = daoMaster.newSession();

		}
		return daoSession;
	}

	public void setDebug() {
		QueryBuilder.LOG_SQL = true;
		QueryBuilder.LOG_VALUES = true;
	}

	/**
	 * 数据库使用完后，必须要进行关闭
	 */
	public void closeConnection() {
		closeHelp();
		closeDaoSession();
	}

	public void closeHelp() {
		if (helper != null) {
			helper.close();
			helper = null;
		}
	}

	public void closeDaoSession() {
		if (daoSession != null) {
			daoSession.clear();
			daoSession = null;
		}
	}
}
